package com.znxs.bs_c.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.znxs.bs_c.common.Status;
import com.znxs.bs_c.entity.Menu;
import com.znxs.bs_c.entity.Role;
import com.znxs.bs_c.entity.User;
import com.znxs.bs_c.entity.dto.UserDTO;
import com.znxs.bs_c.exception.ServiceException;
import com.znxs.bs_c.mapper.RoleMapper;
import com.znxs.bs_c.mapper.UserMapper;
import com.znxs.bs_c.service.IMenuService;
import com.znxs.bs_c.service.IRoleService;
import com.znxs.bs_c.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.znxs.bs_c.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 左拿
 * @since 2023-08-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private static final Log LOG = Log.get();

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private IMenuService menuService;

    @Override
    public UserDTO login(UserDTO userdto) {
        User one = getOne(userdto);
        if (one != null) {
            BeanUtil.copyProperties(one, userdto, true);
            String token = TokenUtils.genToken(one.getId().toString(), one.getPassword());
            // 得到token 存入userDTO
            userdto.setToken(token);

            String roleFlag = one.getRole(); // 获取权限名称

            List<Menu> treeMenusList = getMenusByRoleFlag(roleFlag);
            treeMenusList.forEach(System.out::println);
            //得到menu列表 存入userDTO
            userdto.setMenus(treeMenusList);
            return userdto;
        }else {
            throw new ServiceException(Status.OtherError.getCode(),"用户名或者密码错误");
        }
    }

    @Override
    public User register(UserDTO userdto) {
        User one = getOne(userdto);
        if (one == null) {
            one = new User();
            BeanUtil.copyProperties(userdto, one, true);
            save(one);
            return one;
        }else {
            throw new ServiceException(Status.OtherError.getCode(),"用户名或者密码错误");
        }
    }

    /**
     * 根据usrdto获取User
     * @param userdto
     * @return
     */
    public User getOne(UserDTO userdto){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", userdto.getUsername());
        userQueryWrapper.eq("password", userdto.getPassword());
        User one;
        try {
            one = getOne(userQueryWrapper);
            return one;
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(Status.SystemError.getCode(),Status.SystemError.getMessage());
        }
    }

    public List<Menu> getMenusByRoleFlag(String flag){
        // 获取权限id
        Integer roleId = roleMapper.getRoleIdByFlag(flag);
        // 根据roleId 获取对应的menusList
        List<Integer> menusId = roleMapper.getMenuIdByRoleId(roleId);
        // 进行处理 如果pid 有数字 就插入
        List<Integer> pids = new ArrayList<>();
        for (Integer menuId :menusId) {
            Integer pid = menuService.getById(menuId).getPid();
            // 如果pid 不等于空且 不存在在menusId list里面 就插入
            if (pid!=null && !menusId.contains(pid)){
                pids.add(pid);
            }
        }
        // 添加到menusId list 中
        menusId.addAll(pids);
        // 根据menusId 获取 menus
        List<Menu> menus = menuService.getBaseMapper().selectBatchIds(menusId);
        // 根据menus 返回treeMenus
        List<Menu> treeMenusList = menuService.getTreeMenuList(menus);
        return  treeMenusList;
    }
}
